package bookstore.controller;

import bookstore.handle.Msg;
import bookstore.mapper.AddressMapper;
import bookstore.model.Address;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@RestController
@CrossOrigin
public class AddressController {
    @Autowired
    AddressMapper addressMapper;

    @RequestMapping("/a")
    public Object a(){
        return "a";
    }

    //得到用户所有的地址
    @RequestMapping("/selectAllAddress")
    public Object selectAllAddress(Integer userId) {
        List<Address> list = addressMapper.selectList(new QueryWrapper<Address>().eq("user_id", userId));
        Collections.sort(list, new Comparator<Address>() {
            @Override
            public int compare(Address o1, Address o2) {
                return o2.getId()-o1.getId();
            }
        });
        return new Msg(200, "用户所有的收获地址", list);
    }

    //添加地址
    @RequestMapping("/addOneAddress")
    public Object addOneAddress(Integer userId, String addressStr, String phone, String name) {
        if (userId == null || addressStr == null || null == phone || null == name) {
            return new Msg(0, "请传入有效的地址");
        }
        Address address = new Address(userId, addressStr, phone, name);
        Integer i = addressMapper.insert(address);
        if (i == 1) {
            return new Msg(200, "添加地址成功", address.getId());
        } else {
            return new Msg(0, "添加地址失败");
        }
    }

    //删除地址（可多删）
    @RequestMapping("/delAddress")
    public Object delAddress(String listAddressId) {
        if (listAddressId == null) {
            return new Msg(0, "请传入有效的地址进行删除");
        }
        JSONArray jsonArray=JSONArray.fromObject(listAddressId);
        Integer i = addressMapper.deleteBatchIds(jsonArray);
        if (i != 0) {
            return new Msg(200, "删除成功");
        } else {
            return new Msg(0, "删除失败");
        }
    }
}
